using System.IO;
using System.Text;
using Cysharp.Threading.Tasks;
using Framework.StateMechine;
using UnityEngine;
using UnityEngine.Networking;

namespace Game.Hotfix
{
    public class HotfixResult : StateBase
    {
        private Game.Hotfix.Hotfix hotfix;
        
        public override async UniTask OnEnter(StateArgs _args)
        {
            Debug.Log("hotfix result.");
            
            hotfix = stateMachine.owner as Game.Hotfix.Hotfix;
            await base.OnEnter(_args);

            OpErrorCode();
            await SaveResult();
            
            stateMachine.Change(HotfixState.End);
        }

        private void OpErrorCode()
        {
            if (args == null)
                return;
            
            HotfixArgs arg = args as HotfixArgs;
            Debug.Log("ERROR MSG: " + arg.arg.ToString());
            EventsManager.Instance.Broadcast(new HotfixErrorEvent()
            {
                errMsg = arg.arg.ToString()
            });
        }

        private async UniTask SaveResult()
        {
            WriteVersion();
            WriteChecksum();
            await SaveManifest();
        }
        
        // 写入版本号
        private void WriteVersion()
        {
            if (hotfix.downLoadList.Count <= 0)
                return;
            
            string versionFilename = $"{FileHelper.hotfixFolder}/{HotfixConst.versionFile}";
            FileHelper.CreateDirIfNotExist(FileHelper.hotfixFolder);
            File.WriteAllText(versionFilename, hotfix.hotfixServerDto.version.ToString(), Encoding.UTF8);
            HotfixConst.SetFileNoBackup(versionFilename);
        }
        
        // 写入checksum
        private void WriteChecksum()
        {
            if(hotfix.downLoadList.Count <= 0 || hotfix.remoteChecksumData == null)
                return;

            string hotfixChecksumFile = $"{FileHelper.hotfixFolder}/{FileHelper.checksumHotfixeFile}";
            HotfixConst.WriteAllBytes(hotfixChecksumFile, hotfix.remoteChecksumData, 0, hotfix.remoteChecksumData.Length);
        }
        
        //下载mainfaist
        private async UniTask SaveManifest()
        {
#if (UNITY_ANDROID || UNITY_IOS)
            if (hotfix.downLoadList.Count <= 0)
                return;
            
            DownloadHandler handler = new DownloadHandlerBuffer();
            string remoteManifest = $"{hotfix.hotfixServerDto.url}?version={hotfix.hotfixServerDto.version}&res={FileHelper.targetPlatform}";
            Debug.Log("remote assetbundle manifest path: " + remoteManifest);
            UnityWebRequest request = new UnityWebRequest(remoteManifest, "GET", handler, null);
            request.timeout = 10;               // 设置超时时间
            await request.SendWebRequest();     // 发送请求
            
            HotfixConst.WriteAllBytes(FileHelper.hotfixAssetbundleManifestPath, handler.data, 0, handler.data.Length);
#else
            await UniTask.CompletedTask;
#endif
        }
    }
}